package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.Constant;
import com.example.demo.common.SecurityUtil;
import com.example.demo.common.SessionUtil;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public  Object reg(String username,String password){
        //前端和后端都要进行非空校验
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            return  AjaxResult.fail(-1,"非前端页面请求");
        }
      int result=userService.add(username, SecurityUtil.encrypt(password));//密码加盐
        if(result==1){
            return  AjaxResult.success("添加成功",1);
        }else {
            return AjaxResult.fail(-1, "数据库添加失败");
        }
    }

    @RequestMapping("/login")
    public  int login(HttpServletRequest request,String username, String password){//HttpServletRequest request里保存着session
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            return  0;
        }
        //UserInfo userInfo= userService.login(username,password);
        UserInfo userInfo= userService.getUserByName(username);
        if(userInfo==null||userInfo.getId()<=0){
            return  -1;
        }else {
            boolean result=SecurityUtil.decrypt(password,userInfo.getPassword());
            if(result){
                HttpSession session=request.getSession();//不管有没有都会得到session
                session.setAttribute(Constant.SESSION_USERINFO_KEY,userInfo);
                return  1;
            }
                return -1;
        }
    }

    @RequestMapping("/logout")
    public  boolean logout(HttpServletRequest request){
        HttpSession session =request.getSession(false);
        if(session!=null&&session.getAttribute(Constant.SESSION_USERINFO_KEY)!=null){
            session.removeAttribute(Constant.SESSION_USERINFO_KEY);
        }
        return  true;
    }

    @RequestMapping("/myinfo")
    public  UserInfo myInfo(HttpServletRequest request){
        UserInfo userInfo=SessionUtil.getLoginUser(request);
        if(userInfo!=null){
            return userInfo;
        }
        return  null;
    }
    @RequestMapping("/myinfo2")
    public  UserInfo myInfo2(Integer id){
        if(id!=null&&id>0){
            UserInfo userInfo=userService.myInfo2(id);
            return  userInfo;
        }
        return null;
    }
}
